# coding: utf-8
#--------------------#
# Coder  : Dzlua
# Email  : 505544956@qq.com
# module : scheduler
# file   : database.py
# Time   : 2017/09/29
#--------------------#
import MySQLdb

#--------------------#
class DataBase:
    showinfo = False
    #
    def __enter__(self):
        return self
    def __exit__(self, type, value, trace):
        self.close()
    def __init__(self, host, user, pwd, db, showinfo=True):
        self.showinfo = showinfo
        self.__db = MySQLdb.connect(host=host,user=user,passwd=pwd,db=db,charset="utf8")
        if self.showinfo:
            print('[database] open ok. host: %s, user: %s, db: %s' % (host, user, db))
        self.__dbname = db
    def close(self):
        self.__db.close()
        if self.showinfo:
            print('[database] close ok. db: %s' % (self.__dbname))
    def execute(self, *args, **kwargs):
        if self.showinfo:
            try:
                print('[database] execute: ' + args[0] % args[1])
            except:
                print('[database] execute: ' + args[0])
        cursor = self.__db.cursor()
        try:
            cursor.execute(*args, **kwargs)
            self.__db.commit()
            result = cursor.fetchall()
        except MySQLdb.Error, e:
            self.__db.rollback()
            msg = "[database] execute Error: %d: %s. db: " + self.__dbname + " sql: "
            try:
                print(msg + args[0] % (e.args[0], e.args[1], args[1]) )
            except:
                print(msg + args[0] % (e.args[0], e.args[1]) )
        cursor.close()
        return result
    def save(self, fun_save, data, args = None):
        return fun_save(self.__db, data, args)
    def read(self, fun_read, args = None):
        return fun_read(self.__db, args)
    def to_binary(self, data):
        return MySQLdb.Binary(data)
#--------------------#
